package cn.lichenes.service.impl;

import cn.lichenes.entity.Collect;
import cn.lichenes.entity.Phone;
import cn.lichenes.entity.User;
import cn.lichenes.repository.CollectRepository;
import cn.lichenes.service.CollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;

@Service
public class CollectServiceImpl implements CollectService{

    @Autowired
    private CollectRepository collectRepository;

    public boolean add(User user, Integer pid) {
        Collect collect = new Collect();
        Phone phone = new Phone();
        phone.setpId(pid);
        collect.setUser(user);
        collect.setPhone(phone);
        Collect collect1 = collectRepository.save(collect);
        if (collect1 != null){
            return true;
        }
        return false;
    }

    public Page<Collect> findAll(User user, Integer page) {
        PageRequest pageRequest = PageRequest.of(page - 1, 6);
        Specification<Collect> specification = new Specification<Collect>() {

            public Predicate toPredicate(Root<Collect> root, CriteriaQuery<?> query, CriteriaBuilder criteriaBuilder) {
                return criteriaBuilder.equal(root.get("user").as(user.getClass()),user);
            }
        };
        return collectRepository.findAll(specification, pageRequest);
    }

    public boolean delete(Integer id) {
        collectRepository.deleteById(id);
        return true;
    }
}
